// pages/upload/upload.js

const app = getApp();

// import {
//   request,
//   uploadFile
// } from '../../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 图片显示数组
    imgList: [],
    imgTmpList: [], //图片元信息存储数组
    // 图片压缩
    compression: [],
    //  拖拽图片
    imageWitdh: 0,
    x: 0, // movable-view的坐标
    y: 0,
    areaHeight: 0, // movable-area的高度
    hidden: true, // movable-view是否隐藏
    currentImg: '', // movable-view的图片地址
    currentIndex: 0, // 要改变顺序的图片的下标
    pointsArr: [], // 每张图片的坐标
    flag: true, // 是否是长按
    scrollTop: 0, // 滚动条距离顶部的距离
  },

  // 计算图片宽度
  _handleComputedImage(e) {
    const windowWidth = app.globalData.systemInfo.windowWidth;
    const width = windowWidth - 16;
    const imageWitdh = (width - 16) / 3;
    this.setData({
      imageWitdh: imageWitdh.toFixed(0)
    })
  },

  // 计算movable-area的高度
  _handleComputedArea(e) {
    let that = this;
    wx.createSelectorQuery().selectAll('.image-choose-container').boundingClientRect(function (rect) {
      that.setData({
        areaHeight: rect[0].height
      })
    }).exec()
  },

  // 计算每张图片的坐标
  _handleComputedPoints(e) {
    let that = this;
    let query = wx.createSelectorQuery();
    let nodesRef = query.selectAll(".image-item");
    nodesRef.fields({
      dataset: true,
      rect: true
    }, (result) => {
      that.setData({
        pointsArr: result
      })
    }).exec()
  },

  // 长按图片
  handleLongTap(e) {
    // 计算每张图片的坐标
    this._handleComputedPoints();
    this.setData({
      currentImg: e.currentTarget.dataset.url,
      currentIndex: e.currentTarget.dataset.index,
      hidden: false,
      flag: true,
      x: e.currentTarget.offsetLeft,
      y: e.currentTarget.offsetTop
    })
  },

  // 移动的过程中
  handleTouchMove(e) {
    let x = e.touches[0].pageX;
    let y = e.touches[0].pageY;
    // 首先先获得当前image-choose-container距离顶部的距离
    let that = this;
    wx.createSelectorQuery().selectAll('.image-choose-container').boundingClientRect(function (rect) {
      let top = rect[0].top;
      y = y - that.data.scrollTop - top;
      that.setData({
        x: x,
        y: y,
      })

    }).exec()
  },

  // 移动结束的时候
  handleTouchEnd(e) {
    if (!this.data.flag) {
      // 非长按情况下
      return;
    }
    let x = e.changedTouches[0].pageX;
    let y = e.changedTouches[0].pageY - this.data.scrollTop;
    const pointsArr = this.data.pointsArr;
    let data = this.data.imgList;
    let data2 = this.data.imgTmpList;
    console.log(data, '拖拽改变前图片数组')
    for (let j = 0; j < pointsArr.length; j++) {
      const item = pointsArr[j];
      if (x > item.left && x < item.right && y > item.top && y < item.bottom) {
        const endIndex = item.dataset.index;
        const beginIndex = this.data.currentIndex;
        //临时保存移动的目标数据
        let temp = data[beginIndex];
        let temp2 = data2[beginIndex];
        //将移动目标的下标值替换为被移动目标的下标值
        data[beginIndex] = data[endIndex];
        data2[beginIndex] = data2[endIndex]
        //将被移动目标的下标值替换为beginIndex
        data[endIndex] = temp;
        data2[endIndex] = temp2;
      }
    }
    console.log(data, '拖拽后发生改变后的图片数组')
    this.setData({
      imgList: data,
      imgTmpList: data2,
      hidden: true,
      flag: false,
      currentImg: ''
    })
  },

  // 加号显示操作菜单
  chooseAction() {
    let length = this.data.imgList.length;
    if (length == 9) {
      return wx.showToast({
        title: "亲，最多只能选择九张图哦~",
        icon: "none",
        duration: 2000
      })
    }
    let _this = this;
    wx.showActionSheet({
      itemList: ['拍摄', '从相册选择'],
      success: function (res) {
        if (res.tapIndex === 0) {
          _this.ChooseImage("camera")
        } else if (res.tapIndex === 1) {
          _this.ChooseImage("album")
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },

  // 选择图片
  ChooseImage(sourceType) {
    const length = this.data.imgList.length;
    let imgList = this.data.imgList;
    let tmpList = this.data.imgTmpList;
    const maxSize = 20 * 1024 * 1024;
    let that = this;
    wx.chooseImage({
      count: 9 - length,
      sizeType: ['compressed'],
      sourceType: [sourceType],
      success: (res) => {
        let fileArr = [];
        let paths = [];
        let passed = 0;
        res.tempFiles.map(async (file, idx) => {
          const tempFilesSize = file.size;
          let pass = true;
          // 大于20mb不给选择,过滤掉超过20M的图片
          if (tempFilesSize > maxSize) {
            pass = false;
            wx.showToast({
              title: '不能选择超过20MB大小的图片!',
              icon: 'none',
              duration: 2000
            })
          }
          //判断是否是长图
          that.isLongPic(file.path)
            .then(islong => {
              passed++;
              if (islong != 0) {
                pass = false;
                wx.showToast({
                  title: '请勿选择长图',
                  icon: 'none',
                  duration: 3000
                })
              }
              if (pass) {
                fileArr.push(file);
                paths.push(res.tempFilePaths[idx]);
              }
              if (passed === res.tempFiles.length) {
                // 已经选择一张图片后，进行数组合并
                if (length != 0) {
                  that.setData({
                    imgList: imgList.concat(paths),
                    imgTmpList: tmpList.concat(fileArr) //存储原信息
                  })
                } else {
                  // 第一张图片直接赋值
                  that.setData({
                    imgList: paths,
                    imgTmpList: fileArr //存储原信息
                  })
                }
                // 更新面积
                this._handleComputedArea();
              }
            })
        })
      }
    });
  },

  // 点击查看原图
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  
  // 删除已选
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '亲！确定要删除吗？',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.imgTmpList.splice(e.currentTarget.dataset.index, 1);
          // 更新面积
          this._handleComputedArea();
          this.setData({
            imgList: this.data.imgList,
            imgTmpList: this.data.imgTmpList
          })
        }
      }
    })
  },

  //压缩并上传图片
  uploadCompressImg() {
    const _this = this;
    let compressed = 0;
    let compressedList = [];
    let newList = this.data.imgTmpList;
    console.log(newList, '图片数组')
    newList.map(async (file, idx) => {
      _this.data.compression.push({
        cw: '',
        ch: '',
        canvasShow: false
      })
      let item = newList[idx];
      let tempFilesSize = file.size || 0;
      if (tempFilesSize == 0) {
        //远程图片转本地
        // console.log("远程图片已经下载，无需处理",item);
      } else if (tempFilesSize > 1024 * 50) { //大于50KB,压缩
        //压缩图片
        console.log('else')
        item = await _this.getImageInfo(item, idx);
      }
      compressed++;
      compressedList[idx] = item;
      //最后一个图片上传后提示
      if (compressed === newList.length) { 
        setTimeout(function () {
          wx.showToast({
            icon: 'none',
            title: '所有图片上传成功'
          })
        }, 300)
        compressedList.map((item, index) => {
          if (item) {
            _this.uploadAImage(index + 1, index + 1, item.path ? item.path : item);
          }
        })
      }
    })
  },

  // 获得原始图片大小
  getImageInfo(tempFilePath, idx) {
    const that = this;
    let ctx = [];
    console.log('图片路径和下标', tempFilePath, idx)
    return new Promise(function (resolve) {
      //获得原始图片大小
      wx.getImageInfo({
        src: tempFilePath.path ? tempFilePath.path : tempFilePath,
        success(res) {
          console.log('获得原始图片大小', res.width, res.height)
          let originWidth, originHeight;
          originHeight = res.height;
          originWidth = res.width;
          //压缩比例
          // 最大尺寸限制
          let maxWidth = 650,
            maxHeight = 650;
          // 目标尺寸
          let targetWidth = originWidth,
            targetHeight = originHeight;
          //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 要求宽度*(原生图片比例)=新图片尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }
          //尝试压缩文件，创建 canvas
          ctx[idx] = wx.createCanvasContext('firstCanvas' + (idx));
          ctx[idx].clearRect(0, 0, targetWidth, targetHeight);
          //更新canvas大小
          ctx[idx].drawImage(tempFilePath, 0, 0, targetWidth, targetHeight);
          ctx[idx].draw();
          that.data.compression[idx] = {
            cw: targetWidth,
            ch: targetHeight,
            canvasShow: true
          }
          that.setData({
            compression: that.data.compression
          });
          //保存图片
          setTimeout(function () {
            wx.canvasToTempFilePath({
              canvasId: 'firstCanvas' + (idx),
              width: 0,
              height: 0,
              destWidth: targetWidth,
              destHeight: targetHeight,
              fileType: 'jpg',
              quality: 0.6,
              success: (res) => {
                resolve(res.tempFilePath);
              },
              fail(e) {
                console.log(e);
              }
            }, this)
          }, 800);
        },
        fail(e) {
          console.log(e)
        }
      })
    })
  },

  // 长图
  isLongPic(src) {
    const minRate = 1 / 3;
    const maxRate = 3 / 1;
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: src,
        success(res) {
          if (res.width / res.height < minRate) { //图片过长，纵向长图
            resolve(1);
          } else if (res.width / res.height > maxRate) { //图片过宽，横向长图
            resolve(2)
          } else {
            resolve(0);
          }
        }
      })
    })
  },

  //上传单张图片
  uploadAImage(objectId, id, filePath) {
    console.log("上传图片", id, filePath);
    // filePath => 压缩后的本地图片路径
    // 上传图片参数
    // let data = {};
    // let res = {
    //   filePath: filePath,
    //   name: '',
    //   url: '后台地址'
    // }
    // 调用uploadfile全局封装上传接口
    // const returnValue = uploadFile(res);
    // console.log(returnValue)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 计算图片
    this._handleComputedImage();
  },

  // 监听滚动
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})